package com.idbk.chargestation.fragment;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.charge.ActivityCorrectContact;
import com.idbk.chargestation.activity.charge.ActivityCorrectGeography;
import com.idbk.chargestation.activity.charge.ActivityCurrentPointInMap;
import com.idbk.chargestation.activity.pile.ActivityComplainInfo;
import com.idbk.chargestation.activity.pile.ActivityImageScanner;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.app.MyVersion;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonPoint;
import com.idbk.chargestation.bll.pile.PileVendors;
import com.idbk.chargestation.dialog.EAlertDialog;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.MapUtil;
import com.idbk.chargestation.util.NetUtil;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Locale;

/**
 * 充电点详情信息Fragment
 * @author liangzw,lupc
 *
 */
public class FragmentPointDetail extends Fragment implements OnClickListener {

	private View mView;
	private RatingBar mRatingBar;

	private Context mContext;
	private TextView mTextName,tvAddress, tvMark, tvChargePrice, tvServicePrice,
	tvOperator, tvCompany, mTextPointTag;

	/**
	 * 充电点运营商logo
	 */
	private ImageView mImageVendorLogo;

	/**
	 * 充电点 照片区域
	 */
	private ImageView mImagePoint;
	
	private TextView mTextImage;

	private JsonPoint mResult;

	private TextView mImageCount;

	private ImageView mImageVendor;

	private TextView mTextTel;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.fragment_point_detail, container, false);

		mContext = getActivity();

		setupView();

		return mView;
	}

	private void setupView() {
		mRatingBar = (RatingBar) mView.findViewById(R.id.point_detail_ratingbar);
		mTextTel = (TextView)mView.findViewById(R.id.textview_tel);
		mTextTel.setOnClickListener(this);

		mView.findViewById(R.id.point_detail_correct_and_complain).setOnClickListener(this);
		mView.findViewById(R.id.textview_correct).setOnClickListener(this);
		mView.findViewById(R.id.textview_navi).setOnClickListener(this);

		mTextName = (TextView) mView.findViewById(R.id.textview_point_name);
		tvAddress = (TextView) mView.findViewById(R.id.fragment_detail_address);
		tvAddress.setOnClickListener(this);
		tvMark = (TextView) mView.findViewById(R.id.point_detail_mark);
		tvChargePrice = (TextView) mView.findViewById(R.id.point_detail_chargeprice);
		tvServicePrice = (TextView) mView.findViewById(R.id.point_detail_serviceprice);
		tvOperator = (TextView) mView.findViewById(R.id.operator_name);
		tvCompany = (TextView) mView.findViewById(R.id.company_name);
		mTextPointTag = (TextView) mView.findViewById(R.id.textview_point_tag);
		mImageVendorLogo = (ImageView) mView.findViewById(R.id.operator_logo);

		mTextImage = (TextView)mView.findViewById(R.id.textview_image);
		mImageCount = (TextView)mView.findViewById(R.id.textview_imagecount);

		mImagePoint = (ImageView)mView.findViewById(R.id.imageview_point);

		mImageVendor = (ImageView)mView.findViewById(R.id.imageview_pile_tag_vendor);		
	}

	public void notifyDataCallback(JsonPoint result){
		mResult = result;
		String version = MyVersion.getVersion(mContext);
		if (version.equals(MyVersion.VERSION_ZNYD)) {
			//显示 信任标签
			if(result.operatorId == PileVendors.OFFICAL
					|| result.operatorId == PileVendors.YI_DIAN_ZHUANG
					|| result.operatorId == PileVendors.AGENT){
				mImageVendor.setVisibility(View.VISIBLE);
				mImageVendor.setImageResource(R.drawable.ico_map_authority_tag);
			}
		} else {
			mImageVendor.setVisibility(View.GONE);
		}

		//名称
		mTextName.setText(result.name);

		//地址
		tvAddress.setText(result.address);

		//评分
		float mark = Float.parseFloat(result.mark);
		mRatingBar.setRating(mark);//等级
		tvMark.setText("(" + result.mark + "分)");//评分

		//开放方式，是否收费，是否联网
		String tag = String.format(Locale.CHINA, "%s|%s|%s", 
				result.isOpen ? "对外开放":"内部使用",
						result.isFree ? "免费":"收费",
								result.isOnline ? "联网" : "未联网");
		mTextPointTag.setText(tag);

		//电费
		if(result.priceInfo != null){
			tvChargePrice.setText("电费：" + " " + result.priceInfo);
		} else {
			tvChargePrice.setText("电费：免费");
		}

		//服务费
		if(result.serviceFee){
			tvServicePrice.setText("服务费:" + " " + "收费");
		} else {
			tvServicePrice.setText("服务费:" + " " + "免费");
		}

		//运营商
		tvOperator.setText(result.operatorName);//运营商名称
		tvCompany.setText(result.operatorCompany);//公司名称		
		//运营商图标
		String vendorImageURL = ChargeStationURL.getAbsoluteApiUrlFromRoot(result.operatorLogoImage);//获取地址
		Picasso.with(mContext)			
		.load(vendorImageURL)
		.placeholder(R.drawable.ico_preimg_loading)
		.error(R.drawable.ico_preimg_net_error)       
		.into(mImageVendorLogo);

		//充电点图标
		int count = result.imageURLs == null? 0 : result.imageURLs.size();		
		if(count > 0) {						
			//判断是否是wifi环境
			if(NetUtil.isWifi(mContext)){
				mTextImage.setVisibility(View.GONE);
				mTextImage.setOnClickListener(null);
				mImagePoint.setVisibility(View.VISIBLE);
				mImagePoint.setOnClickListener(this);
				mImageCount.setVisibility(View.VISIBLE);
				String str = count + "张";
				mImageCount.setText(str);

				String url = ChargeStationURL.getAbsoluteApiUrlFromRoot(mResult.imageURLs.get(0));
				Picasso.with(mContext)			
				.load(url)
				.placeholder(R.drawable.ico_preimg_loading)
				.error(R.drawable.ico_preimg_net_error)  
				.fit()
				.centerCrop()
				.into(mImagePoint);
			} else {
				//非wifi环境下 点击才显示图片
				mTextImage.setVisibility(View.VISIBLE);
				mTextImage.setOnClickListener(this);
				mImagePoint.setVisibility(View.GONE);
				mImageCount.setVisibility(View.VISIBLE);
				String str = count + "张";
				mImageCount.setText(str);
			}
		} else {
			mTextImage.setVisibility(View.GONE);
			mTextImage.setOnClickListener(null);
			mImagePoint.setVisibility(View.VISIBLE);
			mImageCount.setVisibility(View.GONE);
		}

		//服务电话
		if(result.servicePhone == null || result.servicePhone.equals("")){
			mTextTel.setText("暂不提供电话");
		} else {
			mTextTel.setText(result.servicePhone);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		intent.putExtra(Const.KEY_ID, mResult.id);		
		switch(v.getId()) {
		case R.id.imageview_point:
		case R.id.textview_image:
			if(mResult != null || mResult.imageURLs != null && mResult.imageURLs.size() > 0){
				//如果电桩没有图片，则不能点击
				intent.setClass(mContext, ActivityImageScanner.class);
				intent.putStringArrayListExtra(
						ActivityImageScanner.KEY_URLS,
						new ArrayList<String>(mResult.imageURLs)
						);
				startActivity(intent);
			}
			break;
		case R.id.fragment_detail_address://地址详情
			intent.setClass(mContext, ActivityCurrentPointInMap.class);
			intent.putExtra(JsonPoint.KEY, mResult);
			startActivity(intent);
			break;
		case R.id.textview_tel:
			if(mResult.servicePhone == null || mResult.servicePhone.equals("")){
				Snackbar.make(mView, "该充电点暂不提供电话", Snackbar.LENGTH_SHORT).show();
			} else {
				requestCallService();
			}			
			break;
		case R.id.point_detail_correct_and_complain:
			complainPointInfo();
			break;
		case R.id.textview_correct:
			correctPointInfo();
			break;
		case R.id.textview_navi:
			requestNavi();
			break;
		default:
			break;
		}		
	}
	
	
	private void requestNavi(){
		if (ContextCompat.checkSelfPermission(mContext, 
				Manifest.permission.ACCESS_FINE_LOCATION)
				!= PackageManager.PERMISSION_GRANTED) {
			requestPermissions(
					new String[]{
							Manifest.permission.ACCESS_COARSE_LOCATION,
							Manifest.permission.ACCESS_FINE_LOCATION,
					},
					QEQUEST_NAVI);
		} else {
			MapUtil.startNavi(mContext, mResult.lat, mResult.lng);
		}
	}
	
	public final static int QEQUEST_NAVI = 20;	

	public final static int CALL_PHONE = 11;

	private void requestCallService(){
		if (ContextCompat.checkSelfPermission(mContext, 
				Manifest.permission.CALL_PHONE)
				!= PackageManager.PERMISSION_GRANTED) {
			requestPermissions(
					new String[]{
							Manifest.permission.CALL_PHONE,
					},
					CALL_PHONE);
		} else {
			callService();
		}
	}

	private void callService(){
		Intent intent = new Intent();
		intent.putExtra(Const.KEY_ID, mResult.id);
		intent.setAction(Intent.ACTION_DIAL);
		Uri data = Uri.parse("tel:" + mResult.servicePhone);
		intent.setData(data);
		startActivity(intent);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
			String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		if(requestCode == CALL_PHONE){
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// Permission Granted
				callService();
			} else {
				// Permission Denied
				BaseActivity.showMissingPermissionDialog(getActivity());
			}
		} else if(requestCode == QEQUEST_NAVI){
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// Permission Granted
				MapUtil.startNavi(mContext, mResult.lat, mResult.lng);
			} else {
				// Permission Denied
				BaseActivity.showMissingPermissionDialog(getActivity());
			}
		}
	}


	private void complainPointInfo(){
		final String[] data = new String[]{
				"电桩无法正常使用",
				"充电点信息虚假",
				"费用不合理",
				"充电速度过慢",
				"其他",
		};
		new EAlertDialog(mContext)
		.setItems(data, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent();
				intent.putExtra(Const.KEY_ID, mResult.id);
				intent.setClass(mContext, ActivityComplainInfo.class);
				intent.putExtra(ActivityComplainInfo.KEY_TITLE, data[which]);
				intent.putExtra(ActivityComplainInfo.KEY_COMPLAIN_TYPE, which + 1);
				startActivity(intent);
			}
		})
		.show();
	}

	private void correctPointInfo(){
		String[] data = new String[]{
				"地址信息纠错",
				"开放方式/时间纠错",
				"联系方式纠错",
				"其他",
		};
		new EAlertDialog(mContext)
		.setItems(data, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent();
				intent.putExtra(Const.KEY_ID, mResult.id);
				if(which == 0){
					intent.setClass(mContext, ActivityCorrectGeography.class);
					startActivity(intent);
				} else if(which == 1){
					Snackbar.make(mView, "暂不支持", Snackbar.LENGTH_SHORT).show();
					//					intent.setClass(mContext, ActivityCorrectTime.class);
					//					startActivity(intent);
				} else if(which == 2){
					intent.setClass(mContext, ActivityCorrectContact.class);
					startActivity(intent);
				} else if(which == 3){
					Snackbar.make(mView, "暂不支持", Snackbar.LENGTH_SHORT).show();
				}
			}
		})
		.show();
	}

}
